package com.base.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.base.comm.CommContent;
import com.base.helper.VosHelper;
import com.base.po.param.InfoCustomers;
import com.base.po.param.VosModelList;
import com.base.po.voip.Smsconfigs;
import com.base.po.voip.SmsconfigsExample;
import com.base.po.voip.Users;
import com.base.po.voip.UsersExample;
import com.base.po.voip.UsersExample.Criteria;
import com.base.service.CallbackinfoesService;
import com.base.service.LogsService;
import com.base.service.SmsconfigsService;
import com.base.service.UsersService;
import com.base.utils.GsonUtil;
import com.base.utils.IP;
import com.base.utils.PasswordUtils;

@Controller
@RequestMapping("/admin")
public class content_xiugaicaiwuzhanghao {
	@Autowired
	private LogsService logsService;// log日志
	@Autowired
	private UsersService usersService;
	@Autowired
	private SmsconfigsService smsconfigsService;// 短信配置
	@Autowired
	private CallbackinfoesService callbackinfoesService;// 话单记录

	// 账户信息
	@RequestMapping("/content_xiugaicaiwuzhanghao")
	public ModelAndView index(HttpServletRequest request, @RequestParam(value = "id", required = true) String id)
			throws Exception {

		// 返回ModelAndView
		ModelAndView modelAndView = new ModelAndView();
		if (request.getSession().getAttribute("adminUserId") == null) {
			modelAndView.setViewName("jsp/login");
			return modelAndView;
		}
		if (id == null) {
			modelAndView.setViewName("jsp/datanotfound");
			return modelAndView;
		}
		Users users = usersService.selectByPrimaryKey(id);

		if (users != null) {
			// 设置剩余短信
			SmsconfigsExample smsconfigsExample = new SmsconfigsExample();
			smsconfigsExample.getOredCriteria().add(
					smsconfigsExample.createCriteria().andAgentidEqualTo(users.getId()).andDatastatusEqualTo(true));
			List<Smsconfigs> sms = smsconfigsService.selectByExample(smsconfigsExample);
			if (sms != null && sms.size() > 0) {
				users.setAppstore(sms.get(0).getCount() + "");
			} else {
				users.setAppstore("0");
			}
			// 设计系统消耗
			BigDecimal xh = callbackinfoesService.sumOmoneyParentID(users.getId());
			if (xh == null) {
				users.setKeypath("0");
			} else {
				users.setKeypath(xh + "");
			}
			// TODO 设置话费余额，以及透支
			/**
			 * 测试
			 * 
			 */
			String results = VosHelper.GetVosAccount("{accounts:['" + users.getUsername() + "']}");
			String result1 = VosHelper.GetVosAccount("{accounts:['" + users.getUsername() + "j']}");
			VosModelList v1 = GsonUtil.getObject(results, VosModelList.class);
			VosModelList v2 = GsonUtil.getObject(result1, VosModelList.class);
			if (v2 != null && v2.infoCustomers.length != 0 && v1 != null && v1.infoCustomers.length != 0) {
				InfoCustomers info2 = v2.infoCustomers[0];
				InfoCustomers info1 = v1.infoCustomers[0];
				users.setLinebalance(new BigDecimal(new DecimalFormat("0.00").format(info2.getMoney())));// 线路费
				users.setOverdraft(info2.getLimitMoney().intValue());// 透支
				users.setFreeroute(info1.getFeeRateGroup());// 费率，数据库中已经保存
			} else {
				users.setLinebalance(new BigDecimal(0.00));
				users.setOneagent("0.00");
			}
			users.setPassword(PasswordUtils.decodePWD(users.getPassword()));// 设置明文密码

			// 设置页面进行跳转
			request.setAttribute("users", users);
			modelAndView.setViewName("jsp/content_xiugaicaiwuzhanghao");
			return modelAndView;
		}
		modelAndView.setViewName("jsp/datanotfound");
		return modelAndView;
	}

	String SUCCESS = "success";

	// 更改商户信息
	@RequestMapping(value = "/updateCaiwuUsers", method = RequestMethod.POST)
	public void updateCaiwuUsers(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "id", required = true) String id, String username, String password, String email,
			Date createtime, Date logintime, String loginip, Integer role, Boolean datastatus, String mobile,
			BigDecimal blance, String freeroute, String parentid, String agentlogo, String prefix, String theme,
			Boolean addcard, Boolean nextagent, String androidversion, String androidpath, String iosversion,
			String iospath, Integer regimoney, Date endtime, String pic, BigDecimal dkbl, Boolean isshop, Integer type,
			String shopid, String adid, BigDecimal profitratio, String appkey, String appsecret, BigDecimal linebalance,
			String pid, String dappkey, String sqappkey, Integer overdraft, String appstore, String appid,
			String keypath, String agentprefix, String oneagent, Boolean sxxh, Boolean isauth, Boolean isalipay,
			Boolean isprofit, Boolean isaliprofit, BigDecimal aliprofitratio, BigDecimal aliprofitmoney,
			BigDecimal profitmoney, Integer shopblance, Integer igtype, Integer calltype, String pass, Integer count,
			Integer regishopmoney, Integer regitime, Byte airrecharge, Byte isgrounding) throws Exception {
		// 返回参数
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		String adminUserId = (String) request.getSession().getAttribute("adminUserId");
		String usernamesys = (String) request.getSession().getAttribute("useracc");
		PrintWriter out = response.getWriter();

		List<Users> user = null;
		UsersExample usersExample = new UsersExample();
		Criteria criteria = usersExample.createCriteria();
		criteria.andUsernameEqualTo(username).andDatastatusEqualTo(true);
		user = usersService.selectByExample(usersExample);
		if (user.size() > 0) {
			if (user != null && !id.equals(user.get(0).getId())) {
				logsService.insert(CommContent.TYPE_CREATE, "商户名：" + username, usernamesys + "已存在", true,
						IP.getIpAddr(request));
				out.print("账号名已存在，请重新填写");
				return;
			}
		}

		if (password == null || password.equals("")) {
			out.print("密码不能为空");
			return;
		}

		if (id == null) {
			out.print("浏览器在点击的过程中发现丢失了用户信息，请您刷新重试！");
			return;
		} else {
			int code = 0;
			Users record = new Users(id.trim(), username, PasswordUtils.toPWD(password), email, createtime, logintime,
					loginip, role, datastatus, mobile, blance, freeroute, parentid, agentlogo, prefix, theme, addcard,
					nextagent, airrecharge, androidversion, androidpath, iosversion, iospath, regimoney, regishopmoney, regitime,
					endtime, pic, dkbl, isshop, type, shopid, adid, profitratio, appkey, appsecret, linebalance, pid, dappkey,
					sqappkey, overdraft, appstore, appid, keypath, agentprefix, oneagent, sxxh, isauth, isalipay,
					isprofit, isaliprofit, aliprofitratio, aliprofitmoney, profitmoney, shopblance, igtype, calltype, isgrounding);
			code = usersService.updateByPrimaryKeySelective(record);

			if (code == 1) {
				logsService.insert(CommContent.TYPE_UPDATE, "成功更新了" + record.getUsername() + "的账号状态", usernamesys, true,
						IP.getIpAddr(request));
			} else {
				logsService.insert(CommContent.TYPE_UPDATE, "更新" + record.getUsername() + "的账号状态时失败了", usernamesys,
						true, IP.getIpAddr(request));
				out.print("更改失败，请您重试");
			}

			int codes = 0;
			// 短信充值
			if (count != null) {
				Smsconfigs smsconfigs = smsconfigsService.selectByAgentId(id);
				if (smsconfigs.getCount() == null) {
					smsconfigs.setCount(0);
				}
				smsconfigs.setCount(smsconfigs.getCount() + count);
				codes = smsconfigsService.updateByPrimaryKeySelective(smsconfigs);
				if (codes == 1) {
					logsService.insert(CommContent.TYPE_UPDATE, "成功更新了" + record.getUsername() + "的短信条数", usernamesys,
							true, IP.getIpAddr(request));
				} else {
					logsService.insert(CommContent.TYPE_UPDATE, "更新" + record.getUsername() + "的短信条数", usernamesys,
							true, IP.getIpAddr(request));

				}
			}

			if (code == 1 && codes == 1) {
				out.print(SUCCESS);
			} else {
				out.print("更改失败，请您重试");
			}
			// 系统费用
//			if(linebalance != null) {
//				
//			}
			// 透支费用
//			if(overdraft != null) {
//				
//			}
			// 话费
//			if(blance != null) {
//				
//			}
		}
	}

}
